from datetime import datetime

from flask import Blueprint, session, render_template, request, jsonify, redirect, url_for

from Models import Student, db, Course, CourseSelection

student_bp = Blueprint('student',__name__,url_prefix='/student')


@student_bp.before_request
def check_login():
    # 检查用户是否登录
    if session.get('user_type') !='student':
        return redirect(url_for('login'))
    if session.get('username') is None:
        return redirect(url_for('login'))  # 使用正确的登录端点
# 写路由
@student_bp.route('/')
def student_index():
   student = Student.query.filter_by(username=session['username']).first()
   return render_template('student/message.html', student=student)

@student_bp.route('/message',methods=['GET','POST'])
def save_message():
   data = request.get_json()
   student = Student.query.filter_by(username=session['username']).first()
   # 基础信息更新
   if 'email' in data:
         student.email = data['email'].strip()

   if 'telephone' in data:
         student.telephone = data['telephone'].strip()

   if 'age' in data:
         student.age = int(data['age']) if data['age'] else None

   if 'gender' in data:
         student.gender = data['gender'].strip()

   if 'major' in data:
         student.major = data['major'].strip()

   if 'address' in data:
         student.address = data['address'].strip()
   if data['new_password']:
         student.password = data['new_password'].strip()

      # 提交数据库更新
   db.session.commit()
   return jsonify({
         'success': True,
         'message': '个人资料更新成功'
      })


@student_bp.route('/date',methods=['GET','POST'])
def student_date():
    return render_template('student/date.html')

@student_bp.route('/course_selection',methods=['GET','POST'])
def course_selection():
    available_courses=Course.query.all()
    return render_template('student/course_selection.html',available_courses=available_courses)
@student_bp.route('/course/select/<int:course_id>', methods=['POST'])
def select_course(course_id):
    """学生选课接口"""
    course = Course.query.get_or_404(course_id)
    student = Student.query.filter_by(username=session['username']).first()  # 假设学生模型与User关联
    # 检查是否已选课
    if CourseSelection.query.filter_by(student_id=student.id, course_id=course_id).first():
        return jsonify({
            'success': False,
            'message': '已选择该课程'
        }), 400

    # 创建选课记录
    selection = CourseSelection(
        student_id=student.id,
        course_id=course_id,
        selection_date=datetime.utcnow(),
        status='已选'
    )
    db.session.add(selection)
    db.session.commit()

    return jsonify({
        'success': True,
        'message': '选课成功',
        'course_name': course.course_name
    })

@student_bp.route('/course_ready_selection', methods=['POST','GET'])
def course_ready_selection():
    student = Student.query.filter_by(username=session['username']).first()
    print(student.username)
    selected_courses=student.course_selections

    # print(selections[0].courses.course_name)
    return render_template('student/course_already_selection.html',selected_courses=selected_courses)

@student_bp.route('/course/drop/<int:selection_id>', methods=['POST'])
def drop_course(selection_id):
    selection = CourseSelection.query.get_or_404(selection_id)
    db.session.delete(selection)
    db.session.commit()
    return jsonify({
        'success': True,
    })


@student_bp.route('/logout', methods=['POST'])
def logout():
    try:
        # 检查 CSRF 令牌（如果使用 Flask-WTF 等扩展）
        # verify_csrf_token()

        # 清除会话中的用户信息
        if 'student_id' in session:
            session.pop('student_id', None)
        if 'student_token' in session:
            session.pop('student_token', None)

        # 其他需要清除的会话数据...

        # 返回成功响应
        return jsonify({
            'success': True,
            'message': '退出登录成功'
        }), 200
    except Exception as e:
        # 记录错误日志
        # 返回错误响应
        return jsonify({
            'success': False,
            'message': '退出登录失败，请重试'
        }), 500